import datetime
import json
import sqlite3
import time
from collections import Counter
import requests

# 如果想在更新龙王信息后发送弹幕请补全send函数里面的roomid、csrf_token、csrf、cookie
# 然后将主函数里面的两个send取消注释


def send(msg):
    form_data = {
        'color': '16777215',
        'fontsize': '25',
        'mode': '1',
        'msg': msg,
        'rnd': '1584849328',
        'roomid': '',
        'csrf_token': '',
        'csrf': ''
    }
    # 设置cookie值帮助我们在发送弹幕的时候，服务器识别我们的身份
    cookie = {
        'Cookie': ""
    }
    res = requests.post('https://api.live.bilibili.com/msg/send', cookies=cookie, data=form_data)
    print(res.status_code)


last_hour = 25
while True:
    try:
        a_time = time.strftime('%H', time.localtime(time.time()))
        m_time = time.strftime('%M', time.localtime(time.time()))
        date = datetime.date.today() + datetime.timedelta(-1)
        if int(m_time) != 00 and int(a_time) != 00:
            con = sqlite3.connect("talk.db")
            cur = con.cursor()
            cur.execute("CREATE TABLE IF NOT EXISTS talk(t_date TEXT PRIMARY KEY, m_count INTEGER,name TEXT)")
            name_list = []
            info_list = []
            for line in open(str(date) + "(new).txt", encoding='utf-8'):
                if " " not in line:
                    print("出现无内容行")
                else:
                    data = line.split(" ", 3)
                    if data[1] == '[收到弹幕]':
                        name_list.append(data[2])
            most_active = Counter(name_list).most_common(1)
            url = 'https://api.bilibili.com/x/space/acc/info?mid=' + str(most_active[0][0])
            data = requests.get(url)
            n_data = json.loads(data.text, encoding="utf-8")
            msg0 = "昨天轮播间老王为" + str(n_data['data']['name'])
            msg1 = "共发送 " + str(most_active[0][1]) + " 条弹幕"
            cur.execute("INSERT INTO talk values(?,?,?)", (date, str(most_active[0][1]), str(n_data['data']['name'])))
            con.commit()
            cur.close()
            con.close()
            print(msg0 + "," + msg1)
            # send(msg0)
            time.sleep(1)
            # send(msg1)
            time.sleep(60)
        print(str(a_time) + ":" + str(m_time))
        time.sleep(45)

    except Exception as e:
        print(e)
        time.sleep(60)
